package com.yiren.dbaa.module.device.model;

import android.app.Activity;

import com.yiren.backstage.communication.api.impl.SerialCommunicationApiImpl;
import com.yiren.backstage.communication.interfaces.DataCallback;
import com.yiren.backstage.communication.thread.RTKConnection;
import com.yiren.backstage.communication.utils.MessagesUtil;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.SignalSourceConfigBean;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.module.device.bean.DeviceMessageBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.module.device.contract.DeviceConnectContract;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.util.CustomerServiceUtil;

import org.apache.commons.lang.StringUtils;

/**
 * Created by WANGRONGXIANG
 * on 2022/6/20
 * Describe
 */
public class DeviceConnectModel implements DeviceConnectContract.Model {

    private Activity activity;

    public DeviceConnectModel(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void startSerialConnect(CommonCallBack callBack) {
        SerialCommunicationApiImpl.getInstance(activity).start();
        SerialCommunicationApiImpl.getInstance(activity).setDataCallback(new DataCallback() {
            @Override
            public void onStateChange(int state, String message) {
                if (message.contains("解析中")){
                    callBack.success("");
                }
            }
        });
    }

    @Override
    public void connectDevice(DeviceConnectContract.DeviceConnectCallback callback) {
        if (CustomerServiceUtil.isCarMachine(activity)) {
            //发送数据下位机
            MessagesUtil messages = new MessagesUtil(MessagesUtil.PARAM, 1, new byte[0], new byte[0]);
            SerialCommunicationApiImpl.getInstance(activity).writeData(messages.getMessage(), "RE_PARAM", new DataCallback() {
                @Override
                public void onSendReadData(String data) {
                    if (StringUtils.isEmpty(data)) {
                        callback.onDeviceConnectFail();
                    } else {
                        G.connectDeviceMessage = analysisDeviceData(data);
                        //TODO:工业电脑内置GPS 启动串口3连接
                        if (null != G.connectDeviceMessage) {
                            SignalSourceConfigBean signalSourceConfig = LoadConfigApi.loadSignalSourceConfig(activity);
                            if (G.connectDeviceMessage.getVersionDescribe().contains("MP")) {
                                signalSourceConfig.setMpDevice(true);
                            } else {
                                signalSourceConfig.setMpDevice(false);
                            }
                            ParamConfigApi.saveSignalSourceConfig(activity, signalSourceConfig);
                        }
                        callback.onDeviceConnectSuccess();
                        //设备连接成功后，向主控机发送一体机的指令：$AT+YTJ\r\n,一秒发一次，最多发3次，返回$AT+YTJ = OK\r\n则说明是一体机，终止发送指令
                        new Thread(() -> {
                            for (int i = 0; i < 3; i++) {
                                if (SignalGConstant.ISYITIJI) break;
                                SerialCommunicationApiImpl.getInstance(activity).writeData("$AT+YTJ\r\n".getBytes(), "", null);
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                    callback.onDeviceConnectComplete();
                }
            });
        } else {
            if (CustomerServiceUtil.isPad(activity)) {
                //TODO  模拟器调试用
                String model = android.os.Build.MODEL;
                if (model.contains("AN00")) {
                    callback.onDeviceConnectSuccess();
                } else {
                    callback.onDeviceNoSupportAsp();
                }
            } else {
                callback.onDeviceConnectSuccess();
            }
            callback.onDeviceConnectComplete();
        }
    }

    @Override
    public DeviceMessageBean analysisDeviceData(String data) {
        if (null == data || data.equals("fail")) {
            return null;
        } else {
            if (data.contains("RE_PARAM")) {
                String[] split = data.split(";");
                if (split.length < 4) {
                    return null;
                }
                DeviceMessageBean deviceMessage = new DeviceMessageBean();
                //得到版本号描述
                String[] versions = split[1].split("/");
                deviceMessage.setVersionDescribe(versions[0]);
                if (versions[0].contains("GDZ")) {  //如果是固定站，则将RTK停止，防止升级或者标定的时候插入RTK数据，导致不成功
                    RTKConnection.getInstance().stop();
                }
                deviceMessage.setVersionCodeByHost(versions[1]);
                deviceMessage.setEquipmentCode(split[2]);
                deviceMessage.setEquipmentMac(split[3]);
                return deviceMessage;
            }
        }
        return null;
    }
}
